package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dao.NodeDao;
import com.itheima.dao.RegionDao;
import com.itheima.entity.Node;
import com.itheima.entity.Region;
import com.itheima.entity.dto.RegionDto;
import com.itheima.entity.vo.PageVo;
import com.itheima.service.NodeService;
import com.itheima.service.RegionService;
import com.itheima.web.exception.BusinessException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 运营区域业务层实现类
 *
 * @Author: LiJinLong
 * @Date: 2022-08-17  14:29
 * @Description:
 */
@Service
public class RegionServiceImpl extends ServiceImpl<RegionDao, Region> implements RegionService {
    @Autowired
    RegionDao regionDao;
    @Autowired
    NodeDao nodeDao;
    @Autowired
    NodeService nodeService;

    @Override
    public PageVo<RegionDto> SelectPage(Long pageIndex, Long pageSize, String name) {
        Page<Region> Page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<Region> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(name), Region::getName, name);
        this.page(Page, queryWrapper);

        ArrayList<RegionDto> list = new ArrayList<>();
        LambdaQueryWrapper<Node> wrapper = new LambdaQueryWrapper<>();
        int count = nodeService.count(wrapper);

        List<Region> regionList = Page.getRecords();
        for (Region region : regionList) {
            RegionDto regionDto = new RegionDto();
            BeanUtils.copyProperties(region, regionDto);
            regionDto.setNodeCount(count);
            list.add(regionDto);
        }
        PageVo<RegionDto> pageVo = new PageVo<>();
        pageVo.setCurrentPageRecords(list);
        pageVo.setPageSize(pageSize);
        pageVo.setPageIndex(pageIndex);
        pageVo.setTotalPage(Page.getTotal());
        return pageVo;
    }

    @Override
    public Boolean add(RegionDto regionDto) {
        regionDto.setName(regionDto.getRegionName());
        regionDto.setRemark(regionDto.getRemark());
        int insert = regionDao.insert(regionDto);
        return insert > 0;
    }

    @Override
    public Boolean update(Region region) {
        return this.updateById(region);
    }

    @Override
    public Boolean delete(Long id) {
        LambdaQueryWrapper<Node> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(id != null, Node::getId, id);
        if (nodeService.count(queryWrapper) > 0) {
            throw new BusinessException("该区域关联了点位，无法删除");
        }

        return this.removeById(id);
    }
}
